using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Threading;
using System.Runtime.InteropServices;

namespace csammisrun.OscarLib.Utility
{
	internal class ProcessQueue
	{
		Queue<DataPacket> _processqueue = new Queue<DataPacket>();
		Timer _processtimer;

		public ProcessQueue()
		{
			_processtimer = new Timer(
				new TimerCallback(SendQueue),
				null, 100, 100);
		}

		/// <summary>
		/// Enqueues a data packet to be processed by SNAC handling functions
		/// </summary>
		/// <param name="dp">A <see cref="DataPacket"/> object</param>
		public void Enqueue(DataPacket dp)
		{
      lock (this)
      {
        _processqueue.Enqueue(dp);
      }
		}

		/// <summary>
		/// Sends the contents of the dispatch queue
		/// </summary>
		/// <param name="threadstate">Always <c>null</c></param>
    protected void SendQueue(object threadstate)
    {
      lock (this)
      {
        while (_processqueue.Count > 0)
        {
          DataPacket dp = _processqueue.Dequeue();
          if (Session.SessionLoginComplete)
          {
            ThreadPool.QueueUserWorkItem(new WaitCallback(SNACFunctions.ProcessSNAC), dp);
          }
          else
          {
            // We have to synchronously process login packets
            // because it's a pretty rigorous call-response format
            SNACFunctions.ProcessSNAC(dp);
          }
        }
      }
    }
	}
}
